import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { WebCount, WebInfo } from "@/types/webInfo";
import { queryWebCount, queryWebInfo } from "@/api/webInfo.api";

/**
 * 异步获取网站信息的 thunk 函数
 */
export const getWebInfo = createAsyncThunk(
  "webInfo/getWebInfo",
  async (): Promise<WebInfo> => {
    const res = await queryWebInfo();
    // 根据响应码返回网站信息或初始化对象
    if (res.code === 200) {
      return res.data || new WebInfo();
    }
    return new WebInfo();
  }
);
/**
 * 异步获取网站统计信息的 thunk 函数
 */
export const getWebCount = createAsyncThunk(
  "webInfo/getWebCount",
  async (): Promise<WebCount> => {
    const res = await queryWebCount();
    // 根据响应码返回网站统计信息或初始化对象
    if (res.code === 200) {
      return res.data || new WebCount();
    }
    return new WebCount();
  }
);

// 定义 redux slice
export const webInfoSlice = createSlice({
  name: "webInfo",
  initialState: {
    webInfo: new WebInfo(),
    webCount: new WebCount(),
  },
  reducers: {},
  // 使用 extraReducers 来处理 async thunk 的成功案例
  extraReducers(builder) {
    builder
    .addCase(getWebInfo.fulfilled, (state, action) => {
      // 当 getWebInfo 请求成功时，更新 state 中的 webInfo
      state.webInfo = action.payload;
    });
    builder.addCase(getWebCount.fulfilled, (state, action) => {
      // 当 getWebCount 请求成功时，更新 state 中的 webCount
      state.webCount = action.payload;
    });
  },
});

// 从 slice 生成的 actions，此处省略具体导出

export default webInfoSlice.reducer; // 导出 reducer 供 store 使用